/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.gateway.route;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.lvyh.lightframe.cloud.common.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * nacos路由数据源
 */
public class NacosRouteDefinitionRepository implements RouteDefinitionRepository {
    private static Logger logger = LoggerFactory.getLogger(NacosRouteDefinitionRepository.class);

    private static final String ROUTE_DATA_ID = "lfc-routes";
    private static final String ROUTE_GROUP_ID = "LFC_GATEWAY";

    private ApplicationEventPublisher applicationEventPublisher;

    private NacosConfigProperties nacosConfigProperties;

    public NacosRouteDefinitionRepository(ApplicationEventPublisher applicationEventPublisher, NacosConfigProperties nacosConfigProperties) {
        this.applicationEventPublisher = applicationEventPublisher;
        this.nacosConfigProperties = nacosConfigProperties;
        addListener();
    }

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        try {
            String content = nacosConfigProperties.configServiceInstance().getConfig(ROUTE_DATA_ID, ROUTE_GROUP_ID, 5000);
            List<RouteDefinition> routeDefinitions = !StringUtils.isEmpty(content) ? JsonUtil.toList(content, RouteDefinition.class) : new ArrayList<>(0);

            return Flux.fromIterable(routeDefinitions);
        } catch (NacosException e) {
            logger.error("get route definitions error", e);
        }
        return Flux.fromIterable(CollUtil.newArrayList());
    }

    /**
     * 添加Nacos监听
     */
    private void addListener() {
        try {
            nacosConfigProperties.configServiceInstance().addListener(ROUTE_DATA_ID, ROUTE_GROUP_ID, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
                    logger.info("nacos config has updated, ready to refresh data.");
                }
            });
        } catch (NacosException e) {
            logger.error("nacos register data listener error", e);
        }
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return null;
    }

}
